#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
用户反馈数据模型
为PC端用户反馈管理提供数据支持
"""

from backend.infrastructure.database import db
from datetime import datetime
from enum import Enum

class FeedbackStatus(Enum):
    """反馈状态枚举"""
    PENDING = "pending"      # 待处理
    PROCESSING = "processing"  # 处理中
    RESOLVED = "resolved"    # 已解决
    CLOSED = "closed"        # 已关闭

class Feedback(db.Model):
    """用户反馈记录模型"""
    __tablename__ = 'feedbacks'
    
    id = db.Column(db.Integer, primary_key=True, comment='反馈ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    
    # 反馈基本信息
    title = db.Column(db.String(200), nullable=False, comment='反馈标题')
    content = db.Column(db.Text, nullable=False, comment='反馈内容')
    category = db.Column(db.String(50), nullable=False, comment='反馈分类：bug-错误报告,feature-功能建议,performance-性能问题,ui-界面问题,other-其他')
    priority = db.Column(db.String(20), default='normal', comment='优先级：low-低,normal-普通,high-高,urgent-紧急')
    status = db.Column(db.String(20), default='pending', comment='处理状态：pending-待处理,processing-处理中,resolved-已解决,closed-已关闭')
    
    # 反馈详细信息
    user_agent = db.Column(db.String(500), nullable=True, comment='用户浏览器信息')
    ip_address = db.Column(db.String(45), nullable=True, comment='用户IP地址')
    contact_info = db.Column(db.String(200), nullable=True, comment='联系方式')
    images = db.Column(db.JSON, nullable=True, comment='附件图片')
    
    # 处理信息
    assigned_to = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, comment='分配给管理员ID')
    resolved_at = db.Column(db.DateTime, nullable=True, comment='解决时间')
    resolution = db.Column(db.Text, nullable=True, comment='解决方案')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    user = db.relationship("User", foreign_keys=[user_id], back_populates="feedbacks")
    assigned_admin = db.relationship("User", foreign_keys=[assigned_to])
    replies = db.relationship("FeedbackReply", back_populates="feedback", cascade="all, delete-orphan")
    
    def to_dict(self):
        """转换为字典"""
        # 解析 images 字段（可能是JSON字符串或已是JSON数组）
        parsed_images = None
        if self.images:
            try:
                import json
                if isinstance(self.images, str):
                    parsed_images = json.loads(self.images)
                else:
                    parsed_images = self.images
            except Exception:
                parsed_images = [self.images] if isinstance(self.images, str) else None
        
        return {
            'id': self.id,
            'user_id': self.user_id,
            'title': self.title,
            'content': self.content,
            'category': self.category,
            'priority': self.priority,
            'status': self.status,
            'user_agent': self.user_agent,
            'ip_address': self.ip_address,
            'contact_info': self.contact_info,
            'images': parsed_images,
            'assigned_to': self.assigned_to,
            'resolved_at': self.resolved_at.isoformat() if self.resolved_at else None,
            'resolution': self.resolution,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class FeedbackReply(db.Model):
    """反馈回复记录模型"""
    __tablename__ = 'feedback_replies'
    
    id = db.Column(db.Integer, primary_key=True, comment='回复ID')
    feedback_id = db.Column(db.Integer, db.ForeignKey('feedbacks.id'), nullable=False, comment='反馈ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='回复者ID')
    
    # 回复内容
    content = db.Column(db.Text, nullable=False, comment='回复内容')
    is_admin_reply = db.Column(db.Boolean, default=False, comment='是否为管理员回复')
    images = db.Column(db.JSON, nullable=True, comment='回复附件')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    feedback = db.relationship("Feedback", back_populates="replies")
    user = db.relationship("User")
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'feedback_id': self.feedback_id,
            'user_id': self.user_id,
            'content': self.content,
            'is_admin_reply': self.is_admin_reply,
            'images': self.images,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
